package com.wuxl.ffmpeg;

/**
 * Description:
 *
 * @author 诸葛小猿
 * @date 2024-12-18
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 视频裁剪任务
 */
public class VideoCutTask {

    /**
     * 任务执行
     * @param shell ffmpeg指令
     * @return
     */
    public static void exec(String shell) {
        System.out.println("shell：" + shell);
        BufferedReader bufferedReader = null;
        try {
            Process process = Runtime.getRuntime().exec(shell);

//            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            String line;
//            StringBuilder sb = new StringBuilder();
//            while (null != (line = bufferedReader.readLine())) {
//                if (!line.isEmpty()) {
//                    sb.append(line);
//                }
//            }
//            process.waitFor();

            //使用waitFor()方法时，由于java给进程的输出流分配的缓冲区很小，特别容易发生缓冲区被填满、程序阻塞的问题
            //使用两个线程分别去处理标准输出流和错误输出流，可以有效地解决缓冲区信息阻塞的问题
            threadExec(process.getInputStream());
            threadExec(process.getErrorStream());
            process.waitFor();

            System.out.println("shell执行结束！");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("shell执行IOException：" + e.getMessage());
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.err.println("shell执行InterruptedException：" + e.getMessage());
        } finally {
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 分线程执行
     * @param input 输入流
     */
    private static void threadExec(final InputStream input) {
        new Thread(()->{
            BufferedReader bf = new BufferedReader(new InputStreamReader(input));
            String line = null;
            try{
                while(null != (line = bf.readLine())) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
